package com.didispace.api.consumer.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Scope;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@RestController
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class UploadController {
    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) {
        if (!Objects.isNull(file) && !file.isEmpty()) {
            String oldFileName = file.getOriginalFilename();
            log.info("oldFileName={}", oldFileName);
            String newFileName = UUID.randomUUID() + oldFileName.substring(oldFileName.lastIndexOf("."));
            log.info("newFileName={}", newFileName);
            String bgIconFilePath = "D://Program/Resources/study/";
            File bgIconFile = new File(bgIconFilePath, newFileName);
            try {
                file.transferTo(bgIconFile);
                return "success";
            } catch (Exception e) {
                log.error("Upload file has error:", e);
                return "error";
            }
        }
        return "error";
    }
}
